import { defineStore } from "pinia";
import { getUserType, UserType } from "common/utils/token";
import { query_store_all_nos } from "@/services/store";
import { desensitization } from "common";
let timer = null;
const innerAudioContext = wx.createInnerAudioContext({
  useWebAudioImplement: true,
});
innerAudioContext.src = `${process.env.TARO_APP_ASSETS_BASE}/sound/call.mp3`;
export const useCallStore = defineStore("store_call", {
  state: () => ({
    NoList: [],
  }),
  actions: {
    async update() {
      if (getUserType() !== UserType.store) return;
      return query_store_all_nos().then((res) => {
        if (res.data.length > 0) {
          const newMobile =
            res.data[res.data.length - 1].normal_user_info.mobile;

          const hasRepeat = this.NoList.some(
            (t) => t.normal_user_info.mobile === newMobile
          );
          if (!hasRepeat) {
            innerAudioContext.play();
          }
        }
        this.NoList = res.data.map((item) => {
          item.normal_user_info.mobile_safe = desensitization(
            item.normal_user_info.mobile
          );
          return item;
        });
      });
    },
    // 定时任务
    schedule() {
      const runTask = () => {
        Promise.race([
          this.update(),
          new Promise((resolve) => setTimeout(resolve, 10000)),
        ]).finally(() => {
          timer = setTimeout(runTask, 6000);
        });
        clearTimeout(timer);
      };
      runTask();
    },
  },
});
